package github.sf.fw.tools.db.catalog;

import lombok.Data;

import java.util.List;
import java.util.stream.Collectors;

/**
 * TableModel默认是基于Mysql的SQL语法进行实现的
 *
 * @author zhoup
 * @since 2023/7/26
 */
@Data
public class TableModel implements Fragment {
    protected String tableName;
    protected boolean dropTableStatement = true;
    protected List<ColumnModel> columnModels;
    protected List<String> primaryKeys;

    @Override
    public String getFragment() {
        if (columnModels == null || columnModels.isEmpty()) {
            throw new IllegalArgumentException(tableName + "表对应的列不能为空");
        }

        StringBuilder result = new StringBuilder("CREATE TABLE IF NOT EXISTS " + tableName + " (\n");
        if (dropTableStatement) {
            result.insert(0, "DROP TABLE IF EXISTS " + tableName + ";\n");
        }
        String collect = columnModels.stream().map(ColumnModel::getFragment)
                .map(this::indent)
                .collect(Collectors.joining(",\n"));
        result.append(collect);
        if (primaryKeys != null && !primaryKeys.isEmpty()) {
            result.append(",\n");
            if (primaryKeys.size() == 1) {
                result.append(indent("")).append("PRIMARY KEY (").append(primaryKeys.get(0)).append(")");
            } else {
                String primaryKeyConstraintName = primaryKeys.stream().reduce("pk", (l, r) -> l + "_" + r);
                String collected = primaryKeys.stream().collect(Collectors.joining(",", "(", ")"));
                result.append(indent("")).append("CONSTRAINT ").append(primaryKeyConstraintName).append(" PRIMARY KEY ").append(collected);
            }
        }
        result.append("\n);");
        return result.toString();
    }

    private String indent(String original) {
        return "  " + original;
    }
}
